import { ZExcel } from '../index';
import './run.less';
import { NFont } from '../types';
import { createFont } from '../utils/create-default-value';
import { TableHelper } from '../utils/table-helper';
import { createTools } from './tools';
import { DataHandlePlugin } from '../pugins/data-handle.plugin';


function calculateTextHeight(txt: string, font: NFont.IFont, boundary: {maxWidth: number}) {
    if(font.autoWrap == false) {
        return [txt];
    }
    let canvas = document.createElement('canvas') as HTMLCanvasElement;
    let ctx = canvas.getContext('2d');
    // ctx.font = `${font.style} normal ${font.weight} ${font.size} ${font.family}`;
    ctx.font = `${font.weight} ${font.size}px ${font.family}`;
    let txtLines: string[] = [];
    let tempStr = '';
    let width = 0;
    for(let i = 0; i < txt.length; i++) {
        if(txt[i] == '\n') {
            width = 0;
            txtLines.push(tempStr);
            tempStr = '';
            continue;
        }
        let characterWidth = ctx.measureText(txt[i]).width;
        if(width + characterWidth > boundary.maxWidth) {
            width = 0;
            txtLines.push(tempStr);
            tempStr = txt[i];
        } else {
            tempStr += txt[i];
            width += characterWidth + font.letterSpace;
        }
    }
    txtLines.push(tempStr);
    return txtLines;
}
function render(ctx: CanvasRenderingContext2D, txts: string[], font: NFont.IFont, boundary: {x: number, y: number, width: number, height: number}) {
    let x = 0;
    if(font.horizontally == NFont.EHorizontally.center) {
        x = boundary.x + boundary.width / 2;
    } else if(font.horizontally == NFont.EHorizontally.left) {
        x = boundary.x;
    } else if(font.horizontally == NFont.EHorizontally.right) {
        x = boundary.x + boundary.width;
    }
    for(let i = 0; i < txts.length; i++) {
        ctx.save();
        ctx.beginPath();
        ctx.font = `${font.weight} ${font.size}px ${font.family}`;
        ctx.fillStyle = font.color;
        ctx.textAlign = <any>NFont.EHorizontally[font.horizontally];
        ctx.textBaseline = 'middle';
        ctx.textAlign = <any>NFont.EHorizontally[font.horizontally];
        ctx.fillText(txts[i],x, boundary.y + i*(font.size + (font.lineHeight - font.size) / 2) + font.size / 2);
        console.log(ctx.measureText(txts[i]));
        ctx.stroke();
        ctx.restore();
    }
}
// calculateTextHeight('djfakdjhf放假啊立刻电\n视机法兰克手动阀', createFont({autoWrap: true}), {maxWidth: 40});
export function start() {
    let container = document.createElement('div') as HTMLDivElement;
    container.className = 'container';
    let toolsContainer = document.createElement('div') as HTMLDivElement;
    toolsContainer.className = 'tools';
    let titleEle = document.createElement('div') as HTMLDivElement;
    // titleEle.innerText = 'Z-Table';
    titleEle.className="z-title"
    toolsContainer.appendChild(titleEle);
    // toolsContainer.innerText='z-table';
    container.appendChild(toolsContainer);
    let tableContainer = document.createElement('div') as HTMLDivElement;
    tableContainer.className = 'z-table';
    container.appendChild(tableContainer);
    document.querySelector('body').appendChild(container);
    let ele = document.querySelector('#x-spreadsheet-demo') as HTMLElement;
    let intance = ZExcel.create(tableContainer);
    // console.log(intance);
    let codeMap: {code: number, value: string}[] = [];
    for(let i = 0; i < 26; i++) {
        codeMap.push({code: i, value: String.fromCharCode(65+i)});
    }
    (<any>window).showCode = () => {
        console.table(codeMap);
    }
    const  dataHandle: DataHandlePlugin = intance.activeTable.pluginManager.getPlugin('DataHandlePlugin');
    dataHandle.setData({
        mergeCells: [
            // {row: 0, col: 0, rowspan: 4, colspan: 4}
        ],
        colConf: [{
            col: 3,
            width: 300
        }],
        datas: [
            {
                row: 0,
                cells: [
                    {
                        col: 0,
                        value: 'fasdjfhajds'
                    }
                ]
            },
            {
                row: 3,
                height: 100,
                cells: []
            },
            {
                row: 0,
                cells: [
                    {
                        col: 0,
                        value: 'dfasdfasd'
                    }
                ]
            },
            {
                row: 2,
                height: 100,
                cells: [
                    {
                        col: 1,
                        font: {
                            vertical: 0,
                            color: '#FF0100'
                        },
                        value: 'fasdfa'
                    },
                    {
                        col: 2,
                        font: {
                            vertical: 0,
                            horizontally: 1
                        },
                        value: '的烧'
                    },
                    {
                        col: 4,
                        font: {
                            vertical: 2,
                            horizontally: 1
                        },
                        value: '下部'
                    },
                    {
                        col: 3,
                        fill: {background: {color: '#000'}}
                    }
                ]
            },
            {
                row: 3,
                cells: [
                    {
                        col: 2,
                        value: '中国'
                    },
                    {
                        col: 3,
                        value: '多发点',
                        font: {
                            horizontally: 1
                        }
                    },
                    {
                        col: 4,
                        value: '范德萨发dfadsfadsfadsfadsfasdfadsfasd',
                        font: {
                            horizontally: 1
                        }
                    }
                ]
            },
            {
                row: 4,
                cells: [
                    {
                        col: 3,
                        value: '钉钉',
                        font: {
                            horizontally: 2
                        }
                    }
                ]
            }
        ]
    });
    createTools(intance.activeTable);
        setTimeout(() => {
            var event = document.createEvent("HTMLEvents");
            event.initEvent("resize", true, true);
            window.dispatchEvent(event);
        }, 500);
    return
    let canvas = document.querySelector('.z-canvas-container').querySelector('canvas') as HTMLCanvasElement;
    let ctx = canvas.getContext('2d');
    // drawLine(ctx, {x: 74,y: 20}, {x: 74, y: 100});
    // drawLine(ctx, {x: 74,y: 20}, {x: 200, y: 20});
    // ctx.textAlign = "center";
    // ctx.textBaseline = "middle";
    // ctx.fillText('我是一段会换行的文字啦啦啦', 74, 20);
    // drawTxt(ctx);
    // console.log('\n'.length);
    ctx.rect(20+0.5,20+0.5,60,18);
    ctx.stroke();
    let font = createFont({autoWrap: true, size: 16, horizontally: NFont.EHorizontally.left, weight: 300});
    console.log(font)
    let value = 'dfjakdjhf放假啊立刻电\n视机法兰克手动阀'
    let strs = calculateTextHeight(value, font, {maxWidth: 56});
    console.log(strs)
    render(ctx, strs, font, {x: 21+0.5, y: 21+0.5, width: 58, height: 60});
    // ctx.save();
    // ctx.beginPath();
    // ctx.moveTo(74.5, 20);
    // ctx.lineTo(74.5, 100);
    // ctx.lineWidth = 1;
    // ctx.strokeStyle = '#000000';
    // ctx.stroke();
    // ctx.restore();
}